package Servlets.yz;

import Bean.supplier;
import Util.GokJDBCUtil2;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.*;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;


@WebServlet(name="SupplyFileUpServlet",urlPatterns = "/SupplyFileUpServlet")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 2,  // 2MB
        maxFileSize = 1024 * 1024 * 10,      // 10MB
        maxRequestSize = 1024 * 1024 * 50    // 50MB
)
public class SupplyFileUpServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    // 目标上传文件夹：服务器项目的webapp目录下的upload/contract（避免与其他文件冲突）
    private static final String UPLOAD_FOLDER = "upload/contract";
    private String uploadDirectory;  // 服务器端实际保存路径

    @Override
    public void init() throws ServletException {
        super.init();
        // 初始化上传目录：基于服务器的webapp根路径（运行时路径）
        // getServletContext().getRealPath("/") 获取服务器上webapp的实际路径
        String webappRealPath = getServletContext().getRealPath("/");
        // 拼接服务器保存路径：webapp根路径 + upload/contract
        uploadDirectory = webappRealPath + File.separator + UPLOAD_FOLDER;

        // 确保上传目录存在（服务器端自动创建）
        File uploadDir = new File(uploadDirectory);
        if (!uploadDir.exists()) {
            boolean isCreated = uploadDir.mkdirs();  // 创建多级目录
            if (!isCreated) {
                throw new ServletException("服务器无法创建上传目录: " + uploadDirectory);
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();

        String supplierId = req.getParameter("supplier");  // 获取供应商ID（变量名更清晰）
        try {
            // 验证服务器上传目录有效性
            if (uploadDirectory == null || uploadDirectory.trim().isEmpty()) {
                throw new IllegalArgumentException("服务器上传目录配置无效");
            }

            File uploadDir = new File(uploadDirectory);
            // 检查服务器目录是否存在、是否为目录、是否可写
            if (!uploadDir.exists()) {
                throw new IOException("服务器上传目录不存在: " + uploadDirectory);
            }
            if (!uploadDir.isDirectory()) {
                throw new IOException(uploadDirectory + " 不是服务器上的有效目录");
            }
            if (!uploadDir.canWrite()) {
                throw new IOException("服务器目录不可写，请检查权限: " + uploadDirectory);
            }

            // 处理文件上传（从请求中获取文件）
            Collection<Part> parts = req.getParts();

            writer.println("<h2>文件上传结果</h2>");
            writer.println("<ul>");

            for (Part part : parts) {
                String fileName = getFileName(part);  // 获取上传的文件名
                if (fileName != null && !fileName.isEmpty()) {
                    // 过滤文件名中的特殊字符（防止路径注入）
                    fileName = fileName.replaceAll("[\\\\/:*?\"<>|]", "_");

                    // 服务器保存路径：uploadDirectory + 处理后的文件名
                    String serverFilePath = uploadDirectory + File.separator + fileName;
                    part.write(serverFilePath);  // 写入服务器

                    // 记录相对路径（用于前端访问，而非绝对路径）
                    String relativePath = "/" + UPLOAD_FOLDER + "/" + fileName;  // 如：/upload/contract/xxx.pdf

                    // 写入数据库（存储相对路径，而非服务器绝对路径）
                    LocalDateTime startTime = LocalDateTime.now();
                    LocalDateTime endTime = startTime.plusYears(3);  // 默认有效期3年
                    String sql = "insert into contract " +
                            "(contractname, documentpath, supplierid, startdate, enddate, createtime) " +
                            "values (?, ?, ?, ?, ?, ?)";
                    // 注意：documentpath存储相对路径，而非服务器绝对路径
                    GokJDBCUtil2.update(sql,
                            fileName,        // 合同名（文件名）
                            relativePath,    // 服务器相对路径（用于前端访问）
                            supplierId,      // 供应商ID
                            startTime,       // 开始时间
                            endTime,         // 结束时间
                            startTime);      // 创建时间

                    writer.println("<li>文件 '" + fileName + "' 上传成功！</li>");
                    writer.println("<li>服务器保存路径: " + serverFilePath + "</li>");
                    writer.println("<li>访问路径: " + relativePath + "</li>");
                }
            }

            writer.println("</ul>");
            writer.println("<a href='ContractSServlet'>返回合同管理页</a>");  // 跳回合同列表

        } catch (Exception e) {
            writer.println("<h3>上传失败: " + e.getMessage() + "</h3>");
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }

    // 从Part中提取文件名（兼容不同浏览器）
    private String getFileName(Part part) {
        if (part == null) {
            return null;
        }

        String contentDisposition = part.getHeader("content-disposition");
        if (contentDisposition == null || contentDisposition.isEmpty()) {
            return null;
        }

        // 解析文件名（处理不同浏览器的格式差异）
        String[] items = contentDisposition.split(";");
        for (String item : items) {
            String trimmedItem = item.trim();
            if (trimmedItem.toLowerCase().startsWith("filename")) {
                int eqIndex = trimmedItem.indexOf('=');
                if (eqIndex == -1) {
                    continue;
                }

                String fileName = trimmedItem.substring(eqIndex + 1).trim();
                // 移除文件名前后的引号
                if (fileName.startsWith("\"") && fileName.endsWith("\"")) {
                    fileName = fileName.substring(1, fileName.length() - 1);
                }

                // 仅保留文件名（去除客户端路径）
                int lastSepIndex = fileName.lastIndexOf(File.separator);
                if (lastSepIndex != -1) {
                    fileName = fileName.substring(lastSepIndex + 1);
                }
                // 处理Windows反斜杠
                lastSepIndex = fileName.lastIndexOf("\\");
                if (lastSepIndex != -1) {
                    fileName = fileName.substring(lastSepIndex + 1);
                }

                return fileName.isEmpty() ? null : fileName;
            }
        }
        return null;
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);  // 统一处理GET和POST请求
    }
}